package com.ruoyi.project.zerocarbon.controller;

import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.zerocarbon.domain.DeclarationZhejiang;
import com.ruoyi.project.zerocarbon.domain.DeclareJudge;
import com.ruoyi.project.zerocarbon.domain.vo.DeclarationAuditVo;
import com.ruoyi.project.zerocarbon.mapper.DeclareJudgeMapper;
import com.ruoyi.project.zerocarbon.service.IDeclarationZhejiangService;
import com.ruoyi.project.zerocarbon.service.IDeclareJudgeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 项目评审Controller
 * 
 * @author ruoyi
 * @date 2021-07-31
 */
@Api("评审相关")
@RestController
@RequestMapping("/zerocarbon/judge")
public class DeclareJudgeController extends BaseController
{
    @Autowired
    private DeclareJudgeMapper declareJudgeMapper;
    @Autowired
    private IDeclareJudgeService declareJudgeService;
    @Autowired
    private IDeclarationZhejiangService declarationZhejiangService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private TokenService tokenService;

    /**
     * 评分列表
     */
    @ApiOperation("评分列表")
    @GetMapping("/list")
    public TableDataInfo list(DeclareJudge declareJudge)
    {
        startPage();
        Assert.notNull(declareJudge.getUserId(),"userId不能为空");
        List<DeclareJudge> list = declareJudgeService.selectDeclareJudgeList(declareJudge);
        return getDataTable(list);
    }

    /**
     * 导出项目评审列表
     */
    @GetMapping("/export")
    public AjaxResult export(DeclareJudge declareJudge)
    {
        List<DeclareJudge> list = declareJudgeService.selectDeclareJudgeList(declareJudge);
        ExcelUtil<DeclareJudge> util = new ExcelUtil<DeclareJudge>(DeclareJudge.class);
        return util.exportExcel(list, "项目评审数据");
    }

    /**
     * 获取项目评审详细信息
     */
    @PreAuthorize("@ss.hasPermi('zerocarbon:judge:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(declareJudgeService.selectDeclareJudgeById(id));
    }

    /**
     * 新增项目评审
     */
    @ApiOperation("评分，接口继续使用")
    @PostMapping("/markScore")
    public AjaxResult add(@RequestBody DeclareJudge declareJudge)
    {
        Assert.notNull(declareJudge.getDeclarationId());
//        Assert.notNull(declareJudge.getScore());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        declareJudge.setUserId(loginUser.getUser().getUserId());
        declareJudge.setExpertName(loginUser.getUser().getNickName());
        declareJudge.setExpertNumber(loginUser.getUser().getUserName());
        declareJudge.setGroupName(sysUserMapper.selectRemarkByUserId(loginUser.getUser().getUserId()));
        DeclareJudge model = new DeclareJudge();
        model.setDeclarationId(declareJudge.getDeclarationId());
        model.setExpertNumber(declareJudge.getExpertNumber());
        List<DeclareJudge> declareJudges = declareJudgeService.selectDeclareJudgeList(model);
        if (!CollectionUtils.isEmpty(declareJudges)){
            if (declareJudges.get(0).getStatus() != null && declareJudges.get(0).getStatus() ==2){
                throw new CustomException("评分已提交，不可重复提交");
            }else {
                declareJudge.setId(declareJudges.get(0).getId());
                return toAjax(declareJudgeService.updateDeclareJudge(declareJudge));
            }
        }
        int i = declareJudgeService.insertDeclareJudge(declareJudge);

        //更新时间
        DeclarationZhejiang declarationZhejiang = new DeclarationZhejiang();
        declarationZhejiang.setId(declareJudge.getDeclarationId());
        declarationZhejiangService.updateDeclarationZhejiang(declarationZhejiang);
        return toAjax(i);
    }

    /**
     * 新增项目评审
     */
    @ApiOperation("提交分数,declarationIdList,接口继续使用")
    @PostMapping("/submitScore")
    public AjaxResult submitScore(@RequestBody DeclarationAuditVo declarationAuditVo)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Assert.notNull(loginUser.getUser().getUserName());
        if (!CollectionUtils.isEmpty(declarationAuditVo.getDeclarationIdList())){
            for (Long declarationId:declarationAuditVo.getDeclarationIdList()){
                DeclareJudge declareJudge = new DeclareJudge();
                declareJudge.setDeclarationId(declarationId);
                declareJudge.setExpertNumber(loginUser.getUser().getUserName());
                List<DeclareJudge> declareJudges = declareJudgeMapper.selectDeclareJudgeList(declareJudge);
//                if (CollectionUtils.isEmpty(declareJudges)){
//                    return AjaxResult.error("尚无已提交数据");
//                }
                if (declareJudges.get(0).getStatus() != null && declareJudges.get(0).getStatus() == 2){
                    return AjaxResult.error("评分已提交，不可重复提交");
                }
                for (DeclareJudge model:declareJudges){
                    model.setStatus(2);
                    declareJudgeMapper.updateByDeclarationId(model);
                }
            }
            return AjaxResult.success();
        }
        DeclareJudge declareJudge = new DeclareJudge();
        declareJudge.setExpertNumber(loginUser.getUser().getUserName());
        //TODO 判断是否已提交完
        List<DeclareJudge> declareJudges = declareJudgeMapper.selectDeclareJudgeList(declareJudge);
        if (CollectionUtils.isEmpty(declareJudges)){
            return AjaxResult.error("尚无已提交数据");
        }
        if (declareJudges.size() != declarationAuditVo.getTotal()){
            return AjaxResult.error("请全部评分之后提交");
        }
        if (declareJudges.get(0).getStatus() != null && declareJudges.get(0).getStatus() == 2){
            return AjaxResult.error("评分已提交，不可重复提交");
        }
        for (DeclareJudge model:declareJudges){
            model.setStatus(2);
            declareJudgeMapper.updateByDeclarationId(model);
        }
        return AjaxResult.success();
    }

    /**
     * 修改项目评审
     */
    @PreAuthorize("@ss.hasPermi('zerocarbon:judge:edit')")
    @Log(title = "项目评审", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DeclareJudge declareJudge)
    {
        return toAjax(declareJudgeService.updateDeclareJudge(declareJudge));
    }

    /**
     * 删除项目评审
     */
    @PreAuthorize("@ss.hasPermi('zerocarbon:judge:remove')")
    @Log(title = "项目评审", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(declareJudgeService.deleteDeclareJudgeByIds(ids));
    }
}
